const { ObjectId } = require('mongodb')
const { stateConfig } = require('../config/resState')
const actionDb = require('../manageDb/index')
const { getLastStr } = require('../utils/tool')

// 添加接口
function addValue(req, res) {
	const tableName = getLastStr(req.url)
	const data = req.body;
	let func = 'addOne'
	if (Array.isArray(data)) {
		func = 'addMany'
		data.forEach(item => {
			item.createTime = Date.now();
		})
	} else {
		data.createTime = Date.now();
	}
	actionDb(tableName, data, func).then(result => {
		res.send(result.insertedId || result.insertedIds)
	}).catch(err => {
		console.log(err)
		res.status(stateConfig.fail.code).json({ message: err })
	})
}
// 通过id删除数据
function deleteValueById(req, res) {
	const tableName = getLastStr(req.url)
	const data = req.body;
	const ids = data.map(id => new ObjectId(id))
	actionDb(tableName, ids, 'deleteMany').then(() => {
		res.send({
			status: stateConfig.success.code,
			message: '操作成功',
		})
	}).catch(err => {
		console.log(err)
		res.status(stateConfig.fail.code).json(err)
	})
}
// 更新接口
function updateValue(req, res) {
	const tableName = getLastStr(req.url)
	const data = req.body;
	data.updateTime = Date.now();
	if (data._id) data._id = new ObjectId(data._id)

	actionDb(tableName, data, 'updateOne').then(() => {
		res.send({
			status: stateConfig.success.code,
			message: '操作成功',
		})
	}).catch(err => {
		console.log(err)
		res.status(stateConfig.fail.code).json({ message: err })
	})
}
// 查询接口
function queryValue(req, res) {
	const tableName = getLastStr(req.url)
	const filter = req.body || {};
	if (filter._id) filter._id = new ObjectId(filter._id)

	actionDb(tableName, filter, 'queryMany').then((result) => {
		res.send(result)
	}).catch(err => {
		console.log(err)
		res.send(stateConfig.fail.code).json({ message: err })
	})
}
module.exports = {
	addValue,
	deleteValueById,
	updateValue,
	queryValue
}